<template>
  <el-dialog v-model="dialogVisible" title="文档权限设置" width="600px" :before-close="handleClose">
    <el-form label-width="120px">
      <!-- 没有父节点时的权限设置 -->
      <template v-if="!hasParent">
        <el-form-item label="公开访问">
          <el-switch v-model="form.FIsPublic" @change="handlePublicChange" />
          <span class="tip-text">公开后所有用户均可访问</span>
        </el-form-item>

        <template v-if="!form.FIsPublic">
          <el-form-item label="可见成员">
            <el-button type="primary" size="small" @click="showUserSelector = true">添加成员</el-button>
            <div class="user-list">
              <el-tag v-for="user in selectedUsers" :key="user.FUserId" closable @close="removeUser(user.FUserId)">
                {{ user.FUsername || user.FUserId }}
              </el-tag>
            </div>
          </el-form-item>
        </template>
      </template>

      <!-- 有父节点时的权限设置 -->
      <template v-else>
        <el-form-item label="继承父节点权限">
          <el-switch v-model="form.FInheritParent" @change="handleInheritChange" />
          <span class="tip-text">继承父文件夹的权限设置</span>
        </el-form-item>

        <template v-if="!form.FInheritParent">
          <el-form-item label="可见成员">
            <el-button type="primary" size="small" @click="showUserSelector = true">添加成员</el-button>
            <div class="user-list">
              <el-tag v-for="user in selectedUsers" :key="user.FUserId" closable @close="removeUser(user.FUserId)">
                {{ user.FUsername || user.FUserId }}
              </el-tag>
            </div>
          </el-form-item>
        </template>
      </template>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">保存</el-button>
    </template>

    <!-- 用户选择器弹窗 -->
    <el-dialog v-model="showUserSelector" title="选择可见成员" width="50%" append-to-body>
      <el-transfer
        v-model="selectedUserIds"
        :data="allUsers"
        :props="{
          key: 'FUserId',
          label: 'FUsername'
        }"
        :titles="['所有用户', '已选用户']"
        filterable
      />
      <template #footer>
        <el-button @click="showUserSelector = false">取消</el-button>
        <el-button type="primary" @click="confirmUserSelection">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { setDocVisibilityApi, getDocVisibilityApi } from "@/api/modules/doc";
import { getAllUserList } from "@/api/modules/admin";
import { useDocumentStore } from "@/stores/modules/document";
const documentStore = useDocumentStore();

// 内部状态管理
const dialogVisible = ref(false);
const currentDocId = ref("");
const currentSpaceId = ref("");
const showUserSelector = ref(false);
const hasParent = ref(false);

// 表单数据
const form = ref({
  FIsPublic: false,
  FInheritParent: false,
  FUserIds: [] as string[]
});

// 用户数据
const allUsers = ref<any[]>([]);
const selectedUserIds = ref<string[]>([]);

// 计算属性
const selectedUsers = computed(() => {
  return allUsers.value.filter(user => selectedUserIds.value.includes(user.FUserId));
});

// 暴露给父组件的方法
const open = async (docId: string, spaceId: string, parentId?: string | null) => {
  hasParent.value = !!parentId;
  currentDocId.value = docId;
  currentSpaceId.value = spaceId;
  dialogVisible.value = true;

  // 初始化表单
  form.value = {
    FIsPublic: false,
    FInheritParent: hasParent.value, // 有父节点时默认继承
    FUserIds: []
  };

  await loadData();
};

const close = () => {
  dialogVisible.value = false;
};

// 数据加载
const loadData = async () => {
  try {
    const [visibilityRes, usersRes] = await Promise.all([
      getDocVisibilityApi({ FDocId: currentDocId.value, isAdmin: documentStore.isAdmin }),
      getAllUserList()
    ]);

    // 根据是否有父节点设置不同字段
    if (hasParent.value) {
      form.value.FInheritParent = visibilityRes.data.FInheritParent ?? true;
      form.value.FUserIds = visibilityRes.data.FVisibleUserIds || [];
    } else {
      form.value.FIsPublic = visibilityRes.data.FIsPublic ?? false;
      form.value.FUserIds = visibilityRes.data.FVisibleUserIds || [];
    }

    selectedUserIds.value = [...form.value.FUserIds];
    allUsers.value = usersRes.data;
  } catch (error) {
    ElMessage.error("加载数据失败");
    console.error(error);
  }
};

// 事件处理
const handlePublicChange = (val: any) => {
  if (val) {
    form.value.FUserIds = [];
    selectedUserIds.value = [];
  }
};

const handleInheritChange = (val: any) => {
  if (val) {
    form.value.FUserIds = [];
    selectedUserIds.value = [];
  }
};

const removeUser = (userId: string) => {
  selectedUserIds.value = selectedUserIds.value.filter(id => id !== userId);
  form.value.FUserIds = [...selectedUserIds.value];
};

const confirmUserSelection = () => {
  form.value.FUserIds = [...selectedUserIds.value];
  showUserSelector.value = false;
};

const handleSubmit = async () => {
  try {
    await setDocVisibilityApi({
      FDocId: currentDocId.value,
      FIsPublic: hasParent.value ? false : form.value.FIsPublic, // 有父节点时不设置公开
      FInheritParent: hasParent.value ? form.value.FInheritParent : false, // 无父节点时不设置继承
      FUserIds: form.value.FUserIds,
      isAdmin: documentStore.isAdmin
    });
    ElMessage.success("权限设置已保存");
    close();
  } catch (error) {
    ElMessage.error("保存权限设置失败");
    console.error(error);
  }
};

const handleClose = () => {
  close();
};

// 暴露方法给父组件
defineExpose({
  open,
  close
});
</script>

<style scoped>
.tip-text {
  margin-left: 10px;
  font-size: 12px;
  color: #999999;
}
.user-list {
  margin-top: 10px;
}
.user-list .el-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}
</style>
